<template>
  <el-dialog :title="dialogTitle" :visible.sync="showModelDialogTemp" width="800px" center    :close-on-click-modal="false"
             :before-close="modelFormCanceled">
    <el-form :model="metaDataForm" :ref="metaDataFormRef" :rules="metaDataRules" size="medium" label-width="140px">
      <el-form-item label="设备分类" prop="category">
        <el-select v-model="metaDataForm.category"  clearable filterable class="width-100" @change="getDeviceBrandList">
          <el-option value="all"
                     label="全部"></el-option>
          <el-option v-for="category in categoryData" :key="category.value" :value="category.deviceTypeNo"
                     :label="category.name"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="设备品牌" prop="brand">

        <el-select v-model="metaDataForm.brand"  clearable filterable class="width-100" @change="getMeatName">
          <el-option value="all"
                     label="全部"></el-option>
          <el-option v-for="brand in brandData" :key="brand.value" :value="brand.manufacturerNo" :label="brand.name">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="监控项" prop="dataKey">
        <el-select v-model="metaDataForm.dataKey"  clearable filterable class="width-100" @change="getMeatJson">
          <el-option v-for="metaName in metaNameData" :key="metaName.key" :value="metaName.key" :label="metaName.name">
          </el-option>
        </el-select>

      </el-form-item>
      <el-form-item label="监控项名称" prop="keyName">
        <el-input v-model="metaDataForm.keyName">
        </el-input>
      </el-form-item>
      <el-form-item label="数据包示例" prop="payloadDemo">
        <el-input v-model="metaDataForm.payloadDemo" :rows="5" type="textarea">
        </el-input>
      </el-form-item>
      <el-form-item label="监控项表达式" prop="keyExp">
        <div v-if="!isCheckMeta">
          <el-tag v-for="(param, index) in paramData" :key="index" :value="param.value"
                  :class="`${index > 0 ? 'mar-lft-5' : ''} cursor-pointer`" size="mini"
                  @click="supplyToKeyExp(param.value)">
            {{
              param.name
            }}
          </el-tag>
        </div>
        <el-autocomplete v-model="metaDataForm.keyExp" :fetch-suggestions="fetchKeyExp" :ref="keyExpRef" type="text"
                         class="inline-input width-100" placeholder="请输入监控项表达式" @focus="handleFocus"
                         @blur="handleBlur"
                         @select="handleSelect" @keydown.native="handleFocus">
        </el-autocomplete>
      </el-form-item>
      <el-form-item label="storeKey" prop="storeKey">
        <el-input v-model="metaDataForm.storeKey" type="text" placeholder="请输入storeKey">
        </el-input>
      </el-form-item>

      <el-form-item>
        <span slot="label">
          表达式参数(可选)
          <el-tooltip content="表达式参数变量对应p0、p1" placement="top">
            <em class="font-size-mini font-color-danger">?</em>
          </el-tooltip>
        </span>
        <el-button type="primary" size="mini" @click="addParams">添加参数</el-button>
        <br/>
        <el-card v-show="!stowAndExpand || index === 0" v-for="(item, index) in metaDataForm.params" :key="index"
                 class="mar-top-10" shadow="never">
          <div slot="header" class="clearfix text-align-right">
            <span class="font-size-14 font-weight-normal mar-rgt-10">{{
                item.paramName || "表达式参数" + (index + 1)
              }}</span>
            <el-button type="danger" size="mini" icon="el-icon-delete" circle @click="deleteParams(index, item)">
            </el-button>
          </div>
          <div>
            <el-form size="medium" label-width="100px">
              <el-form-item label="参数名称">
                <el-input v-model="item.paramName" size="mini" type="text" placeholder="请输入参数名称">
                </el-input>
              </el-form-item>
              <el-form-item label="参数Key">
                <el-input v-model="item.paramKey" size="mini" type="text" placeholder="请输入参数Key">
                </el-input>
              </el-form-item>
              <el-form-item label="可选值">
                <el-button v-if="item.paramValues && item.paramValues.length === 0" type="primary" size="mini"
                           @click="addParamsValue(index)">添加可选值
                </el-button>
                <div v-else v-for="(value, vIndex) in item.paramValues || []" :key="vIndex" class="pad-top-5">
                  <el-input v-model="value.value" class="width-32" size="mini" type="text" placeholder="示例:Y">
                  </el-input>
                  <el-input v-model="value.name" class="width-32" size="mini" type="text" placeholder="示例:在线">
                  </el-input>
                  <el-button class="mar-lft-5" size="mini" type="danger"
                             @click="deleteParamsValue(index, vIndex, value)">删除
                  </el-button>
                  <el-button v-if="vIndex === item.paramValues.length - 1" class="mar-lft-5" size="mini" type="primary"
                             @click="addParamsValue(index)">添加一行
                  </el-button>
                </div>
              </el-form-item>
            </el-form>
          </div>
        </el-card>
        <div v-if="metaDataForm.params && metaDataForm.params.length > 1"
             class="stow-and-expand text-align-center cursor-pointer" @click="stowAndExpand = !stowAndExpand">
          <i class="iconfont" :class="
            stowAndExpand
              ? 'icon-zujiantubiao-xinxijiegou-xiangxia'
              : 'icon-zujiantubiao-xinxijiegou-xiangshang'
          "></i>
          <span class="pad-lft-5">{{
              stowAndExpand
                ? "展开（" + metaDataForm.params.length + "）"
                : "收起（" + metaDataForm.params.length + "）"
            }}</span>
        </div>
      </el-form-item>
      <el-form-item prop="ops">
        <span slot="label">
          可选操作
          <el-tooltip content="可选操作对应变量op" placement="top">
            <em class="font-size-mini font-color-danger">?</em>
          </el-tooltip>
        </span>
        <el-checkbox-group v-model="metaDataForm.ops">
          <el-checkbox v-for="opt in optionalData" :key="opt.value" :disabled="opt.disabled" :label="opt.value">{{
              opt.name
            }}
          </el-checkbox>
        </el-checkbox-group>
      </el-form-item>
      <el-form-item>
        <span slot="label">
          可选值
          <el-tooltip content="可选值对应变量px" placement="top">
            <em class="font-size-mini font-color-danger">?</em>
          </el-tooltip>
        </span>
        <el-button v-if="metaDataForm.valueList.length === 0" type="primary" size="mini" @click="addOptionalValue">
          添加可选值
        </el-button>
        <div v-for="(item, index) in metaDataForm.valueList" :key="index" class="pad-top-5">
          <!-- 可选操作为范围内外时输入起始结束值-->
          <span v-if="
            metaDataForm.ops.includes('range') ||
            metaDataForm.ops.includes('outside')
          ">
            <el-input-number v-model="item.value" :min="0" size="small" placeholder="起始值"
                             @change="itemValueChange(item)"></el-input-number>
            <el-input-number v-model="item.endValue" :min="(parseInt(item.value) || 0) + 1" size="small"
                             placeholder="结束值"></el-input-number>
          </span>
          <el-input v-else v-model="item.value" class="width-32" type="text" placeholder="示例:Y"></el-input>
          <el-input v-model="item.name" class="width-32" type="text" placeholder="示例:在线"></el-input>
          <el-button class="mar-lft-5" size="mini" type="danger" @click="deleteOptionalValue(index, item)">删除
          </el-button>
          <el-button v-if="index === metaDataForm.valueList.length - 1" class="mar-lft-5" size="mini" type="primary"
                     @click="addOptionalValue">添加一行
          </el-button>
        </div>
      </el-form-item>
      <el-form-item label="版本号" v-if="status==='edit'">
        <el-input v-model="metaDataForm.ver" :disabled="status==='edit'"></el-input>
      </el-form-item>
      <el-form-item label="备注">
        <el-input v-model="metaDataForm.remark" type="textarea" placeholder="请输入备注"></el-input>
      </el-form-item>
	    <div class="text-align-right">
		    <el-form-item>
			    <el-button size="medium" @click="modelFormCanceled">取消</el-button>
			    <el-button size="medium" type="primary" @click="modelFormSubmitted">提交</el-button>
		    </el-form-item>
	    </div>
    </el-form>
  </el-dialog>
</template>
<script>
  import {msgCode} from "@/config/string";
  import {JSONParse, confirmHandle, messageHandle} from "@/utils";
  import API from "@/api";

  export default {
    props: {
      metaDataForms: {
        type: Object,
        default: {}
      },
      isCheckMeta: {
        type: Boolean,
        default: false
      },
      status: {
        type: String,
        default: 'add'
      },
      showModelDialog: {
        type: Boolean,
        default: false
      },
    },
    data() {
      return {
        metaDataForm: {
          category: "",
          brand: "",
          keyName: "",
          dataKey: "",
          keyExp: "",
          dataType: "string",
          isActive: "Y",
          // dataType: 'string',
          ops: [],
          // paramType: 'string'
          params: [],
          valueList: [],
          remark: "",
          payloadDemo: "",
          storeKey: ""
        },
        categoryData: [],
        brandData: [],
        metaDataFormRef: "metaDataFormRef",
        // 监控表达式
        keyExpRef: "keyExpRef",
        paramData: [
          {name: "参数1", value: "(p0)"},
          {name: "数组索引", value: "[(p0)]"},
          {name: "字符操作", value: " (op) '(px)'"},
          {name: "数字操作", value: " (op) (px)"},
          {name: "等于", value: " == "},
          {name: "#storeKey", value: ""},
        ],
        optionalData: [
          {name: "大于", value: "gt", disabled: false},
          {name: "大于等于", value: "ge", disabled: false},
          {name: "等于", value: "eq", disabled: false},
          {name: "不等于", value: "ne", disabled: false},
          {name: "小于", value: "lt", disabled: false},
          {name: "小于等于", value: "le", disabled: false},
          {name: "范围内", value: "range", disabled: false},
          {name: "范围外", value: "outside", disabled: false},
        ],
        // 监控表达式的相关数据
        keyExpStart: "", // 光标起始位置
        keyExpEnd: "", // 光标结束位置
        newKeyExp: "", // 新的监控表达式
        keyExpArr: [], // 用于代码提示的keys
        keyExpObj: {}, // 存储数据包所有的key
        selectValue: "", // 拿到选项值
        isCopyMeta: false, // 是否复制
        isChecked: false, // 是否点击校验
        checkMatch: "", // 校验结果
        checkValue: "", // 校验值
        stowAndExpand: true,
        metaDataRules: {
          category: [
            {required: true, message: '请选择设备分类', trigger: ['blur']}
          ],
          brand: [
            {required: true, message: '请选择设备品牌', trigger: ['blur']}
          ],
          keyName: [
            {required: true, message: '请填写监控项名称', trigger: ['blur']}
          ],
          dataKey: [
            {required: true, message: '请填写监控项', trigger: ['blur']}
          ],
          keyExp: [
            {required: true, message: '请填写监控项表达式', trigger: ['blur']}
          ],
          ops: [
            {required: true, message: '请填写可选操作', trigger: ['blur']}
          ],
          storeKey: [
            {required: true, message: '请填写storeKey', trigger: ['blur']}
          ],
          payloadDemo: [
            {required: true, message: '请填写数据包示例', trigger: ['blur']},
            {
              validator: (rule, value, callback) => {
                try {
                  JSON.parse(value);
                } catch (err) {
                  callback(new Error('JSON 数据格式错误'));
                }
                callback();
              },
              trigger: 'blur'
            }
          ],
        },
        metaNameData: [],
        brandValue: '',
        categoryValue: '',
        showModelDialogTemp: this.showModelDialog
      };
    },
    created() {
      this.getDeviceTypeList();
    },
    watch: {
      metaDataForms: {
        handler(newValue) {
          if (newValue) {
            const {
              _id = '', category,
              categoryId,
              brandId,
              brand,
              keyName,
              dataKey,
              keyExp,
              dataType = "string",
              isActive = "Y",
              ops = [],
              params = [],
              valueList = [],
              remark,
              storeKey,
              payloadDemo,
              ver
            } = newValue
            this.metaDataForm._id = _id
            this.metaDataForm.category = category
            this.metaDataForm.brand = brand
            this.metaDataForm.keyName = keyName
            this.metaDataForm.keyExp = keyExp
            this.metaDataForm.dataType = dataType
            this.metaDataForm.isActive = isActive
            this.metaDataForm.ops = ops
            this.metaDataForm.params = params
            this.metaDataForm.valueList = valueList
            this.metaDataForm.remark = remark
            this.metaDataForm.storeKey = storeKey
            this.metaDataForm.dataKey = dataKey
            this.metaDataForm.categoryId = categoryId
            this.metaDataForm.brandId = brandId
            this.metaDataForm.ver=ver

            // this.metaDataForm.payloadDemo = JSONParse(payloadDemo)
            //this.metaDataForm.payloadDemo= JSONParse(payloadDemo, null, 4)
            //this.metaDataForm.payloadDemo =
            //JSON.parseb不能入空参
            if (payloadDemo.length > 0) {
              this.metaDataForm.payloadDemo = JSON.stringify(JSON.parse(payloadDemo), null, 4) || ''
            } else {
              this.metaDataForm.payloadDemo = payloadDemo
            }

          }

        },

      },

      'metaDataForm.ops'(val) {
        if (val.includes('range') || val.includes('outside')) {
          this.optionalData.forEach(item => {
            item.disabled = (item.value !== 'range' && item.value !== 'outside');
          });
        } else if (val.length === 0) {
          this.optionalData.forEach(item => {
            item.disabled = false;
          });
        } else {
          this.optionalData.forEach(item => {
            item.disabled = item.value === 'range' || item.value === 'outside';
          });
        }
      },
      'metaDataForm.keyExp'(val) {
        this.keyExpArr = [];
        if (this.dialogShow) {
          if (!val) {
            this.newKeyExp = '';
            return;
          }
          this.handleInput(val);
        }
      },
      status: {
        handler(newValue, oldval) {
          if (newValue == 'edit') {
            this.geteditname()
          }
        },
        deep: true,
        immediate: true
      },
      showModelDialog: {
        handler(newValue) {
          this.showModelDialogTemp = newValue
        },
        deep: true,
        immediate: true
      },
    },
    computed: {
      dialogTitle() {
        var title = ''
        if (this.status == 'add') {
          title = '新增元数据'
        } else if (this.status == 'edit') {
          title = '编辑元数据'
        } else if (this.status == 'copy') {
          title = '复制元数据'
        } else if (this.status == 'check') {
          title = '校验元数据'
        }
        return title
      }

    },
    methods: {
      // 遍历数组对象不为空
      objecAtrtIsEmpty(data) {
        // 如果是数组，遍历数组里面的
        if (Array.isArray(data)) {
          if (data.length == 0) return false;
          return data.every(el => {
            return this.objecAtrtIsEmpty(el);
          });
          // 非空数组
        } else if (Object.prototype.toString.call(data) === "[object Object]" && JSON.stringify(data) !== '{}') {

          //对象or对象数组
          return Object.keys(data).every(key => {
            // 如果对象子元素为数组
            if (Array.isArray(data[key])) {
              if (data[key].length == 0) return false;
              return data[key].every(el => {
                return this.objecAtrtIsEmpty(el);
              });
            } else if (Object.prototype.toString.call(data) === "[object Object]") {
              // 如果0表示不为空的话可以直接用!data
              // 直接用!data,非运算符的话有些值为0的话会被过滤掉
              return data[key] != "" && data[key] != null && data[key] != undefined;
            } else {
              return key != "" && key != null && key != undefined;
            }
          });
        } else if (Object.prototype.toString.call(data) === "[object Object]" && JSON.stringify(data) === '{}') {
          return false;
        } else {
          // 处理单个值
          return data != "" && data != null && data != undefined;
        }
      },

      //编辑时 获取品牌和监控项名称
      geteditname() {
        // 获取类别
        API.deviceType.deviceTypeAll().then((resp) => {
          this.categoryData = resp.data || [];
	        // this.categoryData.unshift({deviceTypeNo: 'all', value: 'all', name: '全部'});
          const category = this.categoryData.find(val => val.deviceTypeNo === this.metaDataForm.category) || {};
          // 获取品牌名称
	        API.manufacturer.manufacturerByDeviceType({deviceType: category.value}).then((resp) => {
            this.brandData = resp.data || [];
	          // this.brandData.unshift({manufacturerNo: 'all', value: 'all', name: '全部'});
            const brand = this.brandData.find(val => val.manufacturerNo === this.metaDataForm.brand) || {};

            let query = {
              deviceType: category.value,
              manufacturer: brand.value
            }
            //获取监控项名称
            API.metadataSetting.getMetaName(query).then(resp => {
	            const {metaData = []} = resp
	            metaData.unshift({
		            key: 'isOnline',
		            name: '在线状态',
		            data: {
			            isOnline: '01'
		            },
		            enum: {
			            mute: [
				            {
					            key: "Y",
					            alias: "在线"
				            },
				            {
					            key: "N",
					            alias: "离线"
				            },
			            ]
		            }
	            });
	            metaData.unshift({key: 'custom', name: '自定义', data: {}});
	            this.metaNameData = metaData;
            });
          });
        });

      },
      //获取json数据包
      getMeatJson(val) {
        const data = this.metaNameData.find((item) => {
          return item.key === val
        })
        this.metaDataForm.storeKey = data.key
        this.metaDataForm.payloadDemo = JSON.stringify(data.data, null, 4)
        if (data.enum) {
          const enumArr = data.enum[Object.keys(data.enum)[0]]
          this.metaDataForm.valueList = enumArr.map(o => {
            return {name: o.alias, value: o.key};//注意要把数组里的所有字段都加上
          });
        } else {
          this.metaDataForm.valueList = []
        }
      },
      //获取设备类别
      getDeviceTypeList() {
        API.deviceType.deviceTypeAll().then((resp) => {
          this.categoryData = resp.data || [];
					// this.categoryData.unshift({deviceTypeNo: 'all', value: 'all', name: '全部'});
        });
      },
      // 根据设备分类获取设备品牌
      getDeviceBrandList(isClear = true) {
        if (isClear) {
          this.metaDataForm.brand = "";
          // this.metaDataForm.keyName = "";
          this.metaDataForm.payloadDemo = ""
          this.metaDataForm.storeKey = ""
          this.metaDataForm.valueList = []
          this.metaDataForm.dataKey = ""
        }
        const category = this.categoryData.find(val => val.deviceTypeNo === this.metaDataForm.category) || {};
        this.categoryValue = category.value
	      if (category.value === 'all') {
		      // this.brandData = [{deviceTypeNo: 'all', value: 'all', name: '全部'}];
	      } else {
		      API.manufacturer.manufacturerByDeviceType({deviceType: category.value}).then((resp) => {
			      this.brandData = resp.data || [];
		      });
	      }
      },
      //获取监控项名称
      getMeatName(isClear = true) {
        if (isClear) {
          // this.metaDataForm.keyName = "";
          this.metaDataForm.payloadDemo = "";
          this.metaDataForm.storeKey = "";
          this.metaDataForm.valueList = []
          this.metaDataForm.dataKey = ""
        }
        const brand = this.brandData.find(val => val.manufacturerNo === this.metaDataForm.brand) || {};
        this.brandValue = brand.value
        let query = {
          deviceType: this.categoryValue,
          manufacturer: brand.value
        }
        API.metadataSetting.getMetaName(query).then(resp => {
					const {metaData = []} = resp
          metaData.unshift({
            key: 'isOnline',
            name: '在线状态',
            data: {
	            isOnline: '01'
            },
	          enum: {
		          mute: [
			          {
				          key: "Y",
				          alias: "在线"
			          },
			          {
				          key: "N",
				          alias: "离线"
			          },
		          ]
	          }
          });
	        metaData.unshift({key: 'custom', name: '自定义', data: {}});
          this.metaNameData = metaData;
        });
      },

      // 点击tag时补充监控表达式
      supplyToKeyExp(val) {
        this.newKeyExp =
          `${this.metaDataForm.keyExp.substring(
            0,
            this.keyExpStart
          )}${val}${this.metaDataForm.keyExp.substring(this.keyExpEnd)}` || "";
        this.metaDataForm.keyExp = this.newKeyExp || "";
        this.$refs[this.keyExpRef].focus();
      },
      fetchKeyExp(queryString, callback) {
        const keyList =
          Object.keys(JSONParse(this.metaDataForm.payloadDemo)) || [];
        let newKeyList = [];
        if (!this.metaDataForm.keyExp) {
          newKeyList =
            keyList.map(function (val) {
              const res = {};
              res.value = `#${val}`;
              return res;
            }) || [];
        } else {
          newKeyList =
            this.keyExpArr.map(function (val) {
              const res = {};
              res.value = val;
              return res;
            }) || [];
        }
        const results = newKeyList;
        callback(results); // 调用 callback 返回数据
      },
      // 获取监控表达式获取焦点时输入框的光标位置
      handleFocus(e) {
        this.keyExpStart = e.srcElement.selectionStart || "";
        this.keyExpEnd = e.srcElement.selectionEnd || "";
      },
      // 获取监控表达式失焦时输入框的光标位置
      handleBlur(e) {
        this.keyExpStart = e.srcElement.selectionStart || "";
        this.keyExpEnd = e.srcElement.selectionEnd || "";
      },
      // 拿到选项值拼接新的表达式
      handleSelect(item) {
        this.selectValue = item.value ? item.value : "";
        this.$refs[this.keyExpRef].focus();
        this.metaDataForm.keyExp =
          `${this.newKeyExp.substring(0, this.keyExpStart)}${this.selectValue
          }${this.newKeyExp.substring(this.keyExpEnd)}` || "";
      },
      // 删除参数
      deleteParams(index, row) {
        // if (this.metaDataForm.params.length <= 1) return;
        confirmHandle({label: `确认要删除参数${row.value || ""}吗?`})
          .then(() => {
            this.metaDataForm.params.splice(index, 1);
          })
          .catch(() => {
          });
      },
      // 添加参数内可选值
      addParamsValue(index) {
        this.metaDataForm.params[index].paramValues.push({value: "", name: ""});
      },
      // 删除参数内可选值
      deleteParamsValue(index, vIndex, row) {
        // if (this.metaDataForm.params[index].paramValues.length <= 1) return;
        confirmHandle({label: `确认要删除参数内可选值${row.value || ""}吗?`})
          .then(() => {
            this.metaDataForm.params[index].paramValues.splice(vIndex, 1);
          })
          .catch(() => {
          });
      },
      // 添加可选值
      addOptionalValue() {
        this.metaDataForm.valueList.push({value: "", name: ""});
      },
      // 删除可选值
      deleteOptionalValue(index, row) {
        // if (this.metaDataForm.valueList.length <= 1) return;
        confirmHandle({label: `确认要删除可选值${row.value || ""}吗?`})
          .then(() => {
            this.metaDataForm.valueList.splice(index, 1);
          })
          .catch(() => {
          });
      },
      // 可选操作范围内外起始值改变时
      itemValueChange(item = {}) {
        const {value = 0, endValue = 0} = item;
        value >= endValue && (item.endValue = item.value + 1);
      },
      // 添加参数
      addParams() {
        this.stowAndExpand = false;
        this.metaDataForm.params.push({
          paramName: "",
          paramKey: "",
          paramType: "string",
          paramValues: [{value: "", name: ""}],
        });
      },
      initModelForm() {
        this.metaDataForm = {

          category: "",
          brand: "",
          keyName: "",
          dataKey: "",
          keyExp: "",
          dataType: "string",
          isActive: "Y",
          ops: [],
          // paramType: 'string'
          params: [],
          valueList: [],
          remark: "",
          payloadDemo: "",
          storeKey: ''
        };
      },
      resetModelForm() {
        this.initModelForm();
        const modelForm = this.$refs[this.metaDataFormRef];
        modelForm && modelForm.resetFields();
      },
      modelFormCanceled() {

        this.showModelDialogTemp = false
        this.$emit("closeDialog", false);
        this.resetModelForm()
      },
      modelFormSubmitted() {
        console.log(this.metaDataForm)
        this.$refs[this.metaDataFormRef].validate((valid) => {
          if (!valid) return;
          if (this.metaDataForm.params.length > 0 && !this.objecAtrtIsEmpty(this.metaDataForm.params)) {
            this.$notify({
              message: '请填写完整表达式参数',
              type: 'error',
              duration: 3000,
            });
            return false
          }
          if (this.metaDataForm.valueList.length > 0 && !this.objecAtrtIsEmpty(this.metaDataForm.valueList)) {
            this.$notify({
              message: '请填写完整可选值',
              type: 'error',
              duration: 3000,
            });
            return false
          }
          this.modelFormLoading = true;
          const parMar = {
            ...this.metaDataForm,
            // payloadDemo: JSONParse(this.metaDataForm.payloadDemo),
            valueList: this.metaDataForm.valueList.map(item => {
              const {endValue = ''} = item;
              if (endValue) {
                return {value: item.value + ',' + endValue, name: item.name};
              } else {
                return {...item};
              }
            }),
            ops: this.metaDataForm.ops.map(item => {
              const opsItem = this.optionalData.find(val => val.value === item) || {};
              return {
                ...opsItem
              };
            })
          };
          if (!this.metaDataForm._id) {
            API.metadataSetting.alarmMetaAdd(parMar).then(resp => {
              messageHandle({code: msgCode.EDIT_SUCCESS, title: '元数据'});
              // this.getMetaDataList();
              this.modelFormCanceled()
              this.$emit("refresh");
            }).catch(err => {
              // this.dialogLoading = false;
            });
          } else {
            parMar['_id'] = this.metaDataForm._id;
            API.metadataSetting.alarmMetaEdit(parMar).then(resp => {
              messageHandle({code: msgCode.EDIT_SUCCESS, title: '元数据'});
              // this.getMetaDataList();
              this.modelFormCanceled()
              this.$emit("refresh");
            }).catch(err => {

            });
          }
        });
      },
    },
  };
</script>
<style scoped lang="less">
  .width-32 {
    width: 32% !important;
    margin-right: 5px;
  }

  .width-16 {
    width: 16% !important;
  }
</style>
